let files = require.context("../pages", true, /\.vue$/);

let repeatRouterArr = files.keys().map((path) => {
  let regExp = /(\/index\.vue|\.vue)$/;
  let common = files(path).default;
  path = path.replace(regExp, "").substring(1);
  return {
    redirect: common.redirect ?? null,
    name: common.name ?? path.substring(1).split("/").join("-"),
    meta: common.meta ?? {},
    path: path.toLowerCase(),
    component: () => import("@/pages" + path),
  };
});
// export default repeatRouterArr;

const convertTree = (repeatRouterArr) => {
  let treeRoues = [];
  repeatRouterArr.forEach((routeObj) => {
    let pathArr = routeObj.path.substring(1).split("/");
    routeObj.id = pathArr.join("-");
    if (pathArr.length >= 1) {
      let pidArr = [...pathArr];
      pidArr.pop();
      routeObj.pid = pidArr.join("-");
    }
  });
  repeatRouterArr.forEach((routeObj) => {
    let parentObj = repeatRouterArr.find((route) => route.id === routeObj.pid);
    if (parentObj) {
      if (!parentObj.children) parentObj.children = [];
      routeObj.path = routeObj.path.split("/").pop();
      parentObj.children.push(routeObj);
    } else {
      treeRoues.push(routeObj);
    }
  });
  return treeRoues;
};

let result = convertTree(repeatRouterArr);
export default result;
